package com.fzfnn.scrapbook.service.impl;

import com.fzfnn.scrapbook.entity.Message;
import com.fzfnn.scrapbook.mapper.MessageMapper;
import com.fzfnn.scrapbook.mapper.UserMapper;
import com.fzfnn.scrapbook.service.MessageService;
import com.fzfnn.scrapbook.util.R;
import com.fzfnn.scrapbook.vo.MessageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, String> redisMail;
    @Override
    public void saveMessage(Message message) {
        messageMapper.saveMessage(message);
    }

    @Override
    public R getPrivateChatList(String token) {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            return R.errorMsg("登录信息无效");
        }
        return R.successData(messageMapper.listPrivateChats(Long.valueOf(userId)));
    }

    @Override
    public R getHistoryMessages(String token, Long receiverId) {
        String senderId = redisMail.opsForValue().get("token:" + token);
        if (senderId == null) {
            return R.errorMsg("登录信息无效");
        }

        List<Message> rawMessages = messageMapper.getHistoryMessages(Long.valueOf(senderId), receiverId);

        String senderName = userMapper.selectUsernameById(Long.valueOf(senderId));
        String receiverName = userMapper.selectUsernameById(receiverId);

        return R.successData(rawMessages.stream().map(m -> {
            MessageVo dto = new MessageVo();
            dto.setSenderId(m.getSenderId());
            dto.setReceiverId(m.getReceiverId());
            dto.setContent(m.getContent());
            dto.setSendTime(m.getSendTime());
            dto.setSenderUsername(senderId.equals(m.getSenderId()) ? senderName : receiverName);
            dto.setReceiverUsername(receiverId.equals(m.getReceiverId()) ? receiverName : senderName);

            return dto;
        }).collect(Collectors.toList()));
    }

    @Override
    public R deleteChatHistory(String token, Long receiverId) {
        if (receiverId == null) {
            return R.errorMsg("参数无效");
        }

        String senderIdStr = redisMail.opsForValue().get("token:" + token);
        if (senderIdStr == null) {
            return R.errorMsg("登录信息无效");
        }

        Long senderId;
        try {
            senderId = Long.parseLong(senderIdStr);
        } catch (NumberFormatException e) {
            return R.errorMsg("用户信息错误");
        }

        int deleted = messageMapper.deleteChatHistory(senderId, receiverId);
        if (deleted == 0) {
            return R.errorMsg("无聊天记录或删除失败");
        }

        return R.successMsg("删除成功");
    }

}